package com.leetcode.q14;

/**
 * <p> description: desc</p>
 *
 * @author tanzc
 * @date 2022/3/30
 **/
public class LongestCommonPrefix {

    public static void main(String[] args) {
        LongestCommonPrefix longestCommonPrefix = new LongestCommonPrefix();
        String[] strs = {"asdfdsf", "asdfdsc", "asdef"};
        System.out.println(longestCommonPrefix.longestCommonPrefix(strs));
    }

    public String longestCommonPrefix(String[] strs) {
        // 将第一个串作为默认前缀
        String prefix = strs[0];
        int i = 1;
        while (i < strs.length) {
            // 每次拿一个新串，并与前缀比较，较短的作为新前缀
            String temp;
            if (prefix.length() > strs[i].length()) {
                temp = prefix;
                prefix = strs[i];
            } else {
                temp = strs[i];
            }
            int len = prefix.length();
            // 新串与前缀取前缀比较，不一致则前缀缩短
            while (len > 0) {
                if (!temp.substring(0, len).equals(prefix)) {
                    prefix = prefix.substring(0, len - 1);
                    len--;
                } else {
                    break;
                }
            }
            // 如果前缀缩没了，那说明匹配不到前缀了
            if (prefix.length() == 0) {
                break;
            }
            i++;
        }
        return prefix;
    }
}
